﻿Imports SecretaryToolData
Imports System.Text
Imports System.IO
Imports vCard

Public Class frmEmail

	Private Sub frmEmail_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
		PopulatePublishers()
		PopulateGroups()

		lstPublishers.SelectedIndices.Clear()
	End Sub

	Private Sub PopulatePublishers()
		Dim publisherCollection As New List(Of VM_PublisherInformation)
		publisherCollection = (From publisher In PublisherData.LocalPublishers Order By publisher.FullName).Select(Function(x) New VM_PublisherInformation(x.PublisherID)).ToList

		lstPublishers.DataSource = publisherCollection
		lstPublishers.DisplayMember = Extensions.GetMemberInfo(Function(x As VM_PublisherInformation) x.FullName).Name
		lstPublishers.ValueMember = Extensions.GetMemberInfo(Function(x As VM_PublisherInformation) x.PublisherID).Name

	End Sub

	Private Sub PopulateGroups()
		Dim groupCollection As VM_Group() = VM_Group.AllGroups.ToArray

		'cmboGroups.DisplayMember = Extensions.GetMemberInfo(Function(x As VM_Group) x.GroupName).Name
		'cmboGroups.ValueMember = Extensions.GetMemberInfo(Function(x As VM_Group) x.GroupID).Name
		'cmboGroups.DataSource = groupCollection

		DirectCast(clbGroups, ListBox).DataSource = groupCollection
		DirectCast(clbGroups, ListBox).DisplayMember = Extensions.GetMemberInfo(Function(x As VM_Group) x.GroupName).Name
		DirectCast(clbGroups, ListBox).ValueMember = Extensions.GetMemberInfo(Function(x As VM_Group) x.GroupID).Name

	End Sub

	Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
		Me.Close()
	End Sub

	Private Sub btnSelect_Click(sender As System.Object, e As System.EventArgs) Handles btnSelect.Click
		Selector()
	End Sub

	Private Sub btnUnselect_Click(sender As System.Object, e As System.EventArgs) Handles btnUnselect.Click
		Selector(True)
	End Sub

	Private Sub Selector(Optional Unselect As Boolean = False)
		Dim matchingIndicies As New List(Of Integer)
		Dim publishersMissingReports As New List(Of PublisherData)

		'figure out what indexes match the checked conditions
		For Each publisher In PublisherData.LocalPublishers

			If chkElders.Checked AndAlso publisher.IsElder Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

			If chkMinisterialServants.Checked AndAlso publisher.IsMinisterialServant Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

			If chkBrothers.Checked AndAlso publisher.IsMale Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

			If chkFamilyHeads.Checked AndAlso publisher.IsFamilyHead Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

			If chkRegularPioneers.Checked AndAlso publisher.IsPioneer Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

			If chkAuxiliaryPioneers.Checked AndAlso publisher.IsRegAuxPioneer Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

			If chkPublishers.Checked AndAlso publisher.ImmersionDate IsNot Nothing Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

			If chkUnbaptizedPublishers.Checked AndAlso publisher.ImmersionDate Is Nothing Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

			If chkGroupOverseers.Checked AndAlso PublisherData.GroupOverseers.Contains(publisher) Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

			If chkMissingCurrentMontsReport.Checked AndAlso PublisherData.PublishersMissingLastMonthsTime.Contains(publisher) Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

			'for processing groups
			Dim selectedGroupIDs As New List(Of Long)

			For Each checkedItem As VM_Group In clbGroups.CheckedItems
				selectedGroupIDs.Add(checkedItem.GroupID)
			Next

			If selectedGroupIDs.Contains(publisher.GroupID) Then
				matchingIndicies.Add(lstPublishers.FindStringExact(publisher.FullName))
			End If

		Next

		'now actually do the selecting or unselecting of the listbox entries
		For Each matchingIndex In matchingIndicies
			If Unselect Then
				lstPublishers.SelectedIndices.Remove(matchingIndex)
			Else
				lstPublishers.SelectedIndices.Add(matchingIndex)
			End If
		Next

	End Sub

#Region "Emails and Notifications"
	Private Sub btnGenerateEmail_Click(sender As System.Object, e As System.EventArgs) Handles btnGenerateEmail.Click
		Dim newMessage As New MailToLinkBuilder

		For Each myPublisher As VM_PublisherInformation In lstPublishers.SelectedItems
			If rdoSingle.Checked Then
				'if we are sending messages one at a time, we'll need to build a new message with every loop iteration
				newMessage = New MailToLinkBuilder
			End If

			If myPublisher.Email <> "" Then

				newMessage.ToAddresses.Add(myPublisher.Email)

			End If

			If lstPublishers.SelectedItems.Count = 1 OrElse rdoSingle.Checked Then
				'if there is only one selected, address the email to them
				newMessage.Body = String.Format("{1},{0}{0}", Environment.NewLine, myPublisher.FullName)
			End If

			If rdoSingle.Checked Then
				'if we are sending messages one at a time, we need to build the message every loop iteration
				Process.Start(newMessage.GetMailToLink())
			End If
		Next

		If rdoMultiple.Checked Then
			'only if we are sending a single (grouped) message do we need to do this here
			'otherwise we did it in the loop
			Process.Start(newMessage.GetMailToLink())
		End If
	End Sub

	Private Sub btnGenerateTextAndEmail_Click(sender As System.Object, e As System.EventArgs) Handles btnGenerateTextAndEmail.Click
		Dim newMessage As New MailToLinkBuilder

		For Each myPublisher As VM_PublisherInformation In lstPublishers.SelectedItems
			If rdoSingle.Checked Then
				'if we are sending messages one at a time, we'll need to build a new message with every loop iteration
				newMessage = New MailToLinkBuilder
			End If

			If myPublisher.Email <> "" Then

				newMessage.ToAddresses.Add(myPublisher.Email)

			End If
			If myPublisher.TextMessageEmail <> "" Then

				newMessage.ToAddresses.Add(myPublisher.TextMessageEmail)

			End If

			If lstPublishers.SelectedItems.Count = 1 OrElse rdoSingle.Checked Then
				'if there is only one selected, address the email to them
				newMessage.Body = String.Format("{1},{0}{0}", Environment.NewLine, myPublisher.FullName)
			End If

			If rdoSingle.Checked Then
				'if we are sending messages one at a time, we need to build the message every loop iteration
				Process.Start(newMessage.GetMailToLink())
			End If
		Next

		If rdoMultiple.Checked Then
			'only if we are sending a single (grouped) message do we need to do this here
			'otherwise we did it in the loop
			Process.Start(newMessage.GetMailToLink())
		End If
	End Sub

	Private Sub btnGenerateTextMessage_Click(sender As System.Object, e As System.EventArgs) Handles btnGenerateTextMessage.Click
		Dim newMessage As New MailToLinkBuilder

		For Each myPublisher As VM_PublisherInformation In lstPublishers.SelectedItems
			If rdoSingle.Checked Then
				'if we are sending messages one at a time, we'll need to build a new message with every loop iteration
				newMessage = New MailToLinkBuilder
			End If

			If myPublisher.TextMessageEmail <> "" Then

				newMessage.ToAddresses.Add(myPublisher.TextMessageEmail)

			End If

			If lstPublishers.SelectedItems.Count = 1 OrElse rdoSingle.Checked Then
				'if there is only one selected, address the email to them
				newMessage.Body = String.Format("{1},{0}{0}", Environment.NewLine, myPublisher.FullName)
			End If

			If rdoSingle.Checked Then
				'if we are sending messages one at a time, we need to build the message every loop iteration
				Process.Start(newMessage.GetMailToLink())
			End If

		Next

		If rdoMultiple.Checked Then
			'only if we are sending a single (grouped) message do we need to do this here
			'otherwise we did it in the loop
			Process.Start(newMessage.GetMailToLink())
		End If
	End Sub

	Private Sub btnSendPioneerStatus_Click(sender As System.Object, e As System.EventArgs) Handles btnSendPioneerStatus.Click
		For Each myPublisher As VM_PublisherInformation In lstPublishers.SelectedItems
			Dim myPublisherData As New VM_PublisherCard(myPublisher.PublisherID)
			If myPublisher.IsPioneer Then

				Dim newMessage As New MailToLinkBuilder
				Dim subject As String = "Pioneer Hours Status"
				Dim body As String = String.Format("{1},{0}{0}As of {2}, you are {3} hour{4} {5} for this service year.{0}{0}Your Brother,{0}Congregation Secretary", Environment.NewLine, myPublisher.FullName, Now.AddMonths(-1).ToString("MMMM, yyyy"), Math.Abs(myPublisherData.PioneerHoursPaceThisServiceYear), If(Math.Abs(myPublisherData.PioneerHoursPaceThisServiceYear) > 1, "s", ""), If(myPublisherData.PioneerHoursPaceThisServiceYear > 0, "ahead", "behind"))

				newMessage.Subject = subject
				newMessage.Body = body

				If myPublisher.Email <> "" Then
					newMessage.ToAddresses.Add(myPublisher.Email)
				End If

				If myPublisher.TextMessageEmail <> "" Then
					newMessage.ToAddresses.Add(myPublisher.TextMessageEmail)
				End If

				Process.Start(newMessage.GetMailToLink())

			End If

		Next

	End Sub
#End Region

	Private Sub btnvCard_Click(sender As System.Object, e As System.EventArgs) Handles btnvCard.Click

		Dim singleFile As Boolean = False
		Dim myvCards As New List(Of KeyValuePair(Of String, String))
		Dim myvCard As vCard2_1
		Dim myPhone As TelephoneNumber
		Dim myAddress As DeliveryLabel
		Dim myNotes As List(Of String)
		Dim sb As StringBuilder
		Dim outputFile As FileInfo

		If lstPublishers.SelectedItems.Count > 1 AndAlso rdoSingle.Checked Then
			singleFile = True
		End If

		For Each publisher As VM_PublisherInformation In lstPublishers.SelectedItems
			myvCard = New vCard2_1
			myNotes = New List(Of String)

			myvCard.vCardItems.Add(New FormattedName(publisher.FullName))
			myvCard.vCardItems.Add(New eMail(publisher.Email))

			myPhone = New TelephoneNumber(publisher.MobileTelephone)
			myPhone.IsCellular = True
			myPhone.IsPreferred = True
			myvCard.vCardItems.Add(myPhone)

			myPhone = New TelephoneNumber(publisher.EmergencyContactInformation.HomeTelephone)
			myPhone.IsHome = True
			myvCard.vCardItems.Add(myPhone)

			myPhone = New TelephoneNumber(publisher.EmergencyContactInformation.WorkTelephone)
			myPhone.IsWork = True
			myvCard.vCardItems.Add(myPhone)

			myAddress = New DeliveryLabel(publisher.EmergencyContactInformation.PhysicalAddress)
			myAddress.IsHome = True
			myAddress.IsWork = False
			myvCard.vCardItems.Add(myAddress)

			myvCard.vCardItems.Add(New Birthdate(publisher.BirthDate))

			If publisher.ImmersionDate IsNot Nothing Then
				myvCard.vCardItems.Add(New X_Anniversary(publisher.ImmersionDate))
			End If

			myvCard.vCardItems.Add(New X_Gender(If(publisher.IsMale, "Male", "Female")))

			'emergency contact information
			myNotes.Add("***Emergency Contact Information***")
			myNotes.Add(String.Empty)
			myNotes.Add(String.Format("Name: {0}", publisher.EmergencyContactInformation.OtherName))
			myNotes.Add(String.Format("Mobile Number: {0}", publisher.EmergencyContactInformation.OtherMobileTelephone))
			myNotes.Add(String.Format("Home Number: {0}", publisher.EmergencyContactInformation.OtherHomeTelephone))
			myNotes.Add(String.Format("Work Number: {0}", publisher.EmergencyContactInformation.OtherWorkTelephone))
			myNotes.Add(String.Format("Email: {0}", publisher.EmergencyContactInformation.OtherEmail))
			myNotes.Add("Special Needs:")
			myNotes.Add(publisher.EmergencyContactInformation.SpecialNeeds)
			myNotes.Add("***End Emergency Contact Information***")
			myNotes.Add(String.Empty)
			'end emergency contact information

			sb = New StringBuilder
			For Each note In myNotes
				sb.AppendLine(note)
			Next
			myvCard.vCardItems.Add(New Comment(sb.ToString))

			myvCards.Add(New KeyValuePair(Of String, String)(publisher.FullName.MakeSafeFileName, myvCard.BuildvCardString))
		Next

		If singleFile Then
			outputFile = New FileInfo(String.Format("{0}\{1}.{2}", ConfigPropertyKeys.AutoBackupLocation, "ExportedContacts".AppendFileDateExtension, "vcf"))

			sb = New StringBuilder
			For Each workingvCard In myvCards
				sb.Append(workingvCard.Value)
			Next

			Using sWriter As New StreamWriter(outputFile.FullName, False)
				sWriter.Write(sb.ToString)
			End Using

			MessageBox.Show(String.Format("vCard created at {0}.", outputFile.FullName), "Export Completed", MessageBoxButtons.OK, MessageBoxIcon.Information)
		Else
			For Each workingvCard In myvCards
				outputFile = New FileInfo(String.Format("{0}\{1}-{2}.{3}", ConfigPropertyKeys.AutoBackupLocation, "ExportedContact", workingvCard.Key.AppendFileDateExtension, "vcf"))

				Using sWriter As New StreamWriter(outputFile.FullName, False)
					sWriter.Write(workingvCard.Value)
				End Using
			Next

			MessageBox.Show(String.Format("vCard(s) created at {0}.", ConfigPropertyKeys.AutoBackupLocation), "Export Completed", MessageBoxButtons.OK, MessageBoxIcon.Information)

		End If

	End Sub

End Class